<template>
	<view class="container">


		<!-- 提示文字 -->
		<view class="tip">
			<u-icon name="warning" size="32" color="#f9ae3d" style="margin-right: 10rpx;"></u-icon>
			<text>请用户绘画一个房子</text>
		</view>

		<!-- 主内容区 -->
		<view class="main-content">
			<!-- 左侧画布区域 -->
			<view class="drawing-wrapper">
				<view class="drawing-area">
					<canvas canvas-id="drawingCanvas" class="drawing-canvas" @touchstart="handleTouchStart"
						@touchmove="handleTouchMove" @touchend="handleTouchEnd"></canvas>
				</view>
			</view>

			<!-- 右侧工具栏 -->
			<view class="toolbar">
				<view class="color-picker">
					<view v-for="color in colors" :key="color" class="color-option" :style="{ 
							backgroundColor: color, 
							border: selectedColor === color ? '2rpx solid #1296db' : '2rpx solid #e4e7ed'
						}" @click="selectColor(color)">
					</view>
				</view>
				<view class="brush-size">
					<text class="label">画笔大小: {{brushSize}}</text>
					<slider :value="brushSize" min="1" max="20" step="1" activeColor="#1296db"
						@change="handleSliderChange" />
				</view>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="action-footer">
			<u-button class="btn" type="primary" shape="circle" @click="clearCanvas">
				清空画布
			</u-button>
			<view class="btn-gap"></view>
			<u-button class="btn" type="success" shape="circle" @click="submitDrawing">
				提交
			</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				colors: [
					'#000000', '#333333', '#666666', '#999999', '#CCCCCC',
					'#FF0000', '#FF6600', '#FFCC00', '#33FF00', '#00FF99',
					'#00FFFF', '#0066FF', '#3300FF', '#CC00FF', '#FF00CC',
					'#FF0066', '#FF5733', '#33FF57', '#3357FF', '#F033FF',
					'#ff557f', '#ffffff', '#aa0000', '#aa557f'
				],
				selectedColor: '#000000',
				brushSize: 5,
				ctx: null,
				isDrawing: false,
				lastX: 0,
				lastY: 0,
				tempFilePath: '',
				startTime: null,
				usedTime:null
			}
		},
		onReady() {
			//开始计时
			this.startTime = Date.now()
			this.initCanvas();
		},
		methods: {
			initCanvas() {
				this.ctx = uni.createCanvasContext('drawingCanvas', this);
				// 设置白色背景
				this.ctx.setFillStyle('#ffffff');
				this.ctx.fillRect(0, 0, 7500, 6000);
				// 初始化画笔
				this.ctx.setStrokeStyle(this.selectedColor);
				this.ctx.setLineWidth(this.brushSize);
				this.ctx.setLineCap('round');
				this.ctx.setLineJoin('round');
				this.ctx.draw();
			},
			handleTouchStart(e) {
				this.isDrawing = true;
				this.lastX = e.touches[0].x;
				this.lastY = e.touches[0].y;
			},
			handleTouchMove(e) {
				if (!this.isDrawing) return;
				const x = e.touches[0].x;
				const y = e.touches[0].y;
				this.ctx.beginPath();
				this.ctx.moveTo(this.lastX, this.lastY);
				this.ctx.lineTo(x, y);
				this.ctx.stroke();
				this.ctx.draw(true);
				this.lastX = x;
				this.lastY = y;
			},
			handleTouchEnd() {
				this.isDrawing = false;
			},
			selectColor(color) {
				this.selectedColor = color;
				this.ctx.setStrokeStyle(color);
			},
			clearCanvas() {
				this.ctx.clearRect(0, 0, 7500, 6000);
				this.ctx.draw(true);
			},
			submitDrawing() {
				// 第一步：canvas 转临时文件路径
				uni.canvasToTempFilePath({
					canvasId: 'drawingCanvas', // 你的 canvas ID
					success: (res) => {
						this.tempFilePath = res.tempFilePath;
						console.log('临时图片路径:', this.tempFilePath);

						// 上传到服务器
						this.uploadToServer(this.tempFilePath);
					},
					fail: (err) => {
						console.error('canvas 转图片失败:', err);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				}, this);
			},

			uploadToServer(filePath) {
				const token = uni.getStorageSync('token'); // 直接取本地缓存 token
				uni.uploadFile({
					url: 'http://ip-pppoe-liaoning-07.xyzy.eu.org:5532/common/upload', // 你后端的上传地址
					filePath: filePath,
					name: 'file', // 后端接收字段名
					header: {
						'Authorization': 'wx' + token, // 如果后端要求 Authorization
					},
					success: (uploadRes) => {
						console.log('上传成功:', uploadRes);
						const data = JSON.parse(uploadRes.data); // 若返回 JSON 字符串
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
						const result = JSON.parse(uploadRes.data);
						console.log(result);
						const aiUrl = result.url
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						});

						if (this.startTime) {
							console.log('111')
							const startTime1 = (typeof this.startTime === 'number' && this.startTime < 1e12) ?
								this.startTime * 1000 :
								this.startTime;
							const endTime = Date.now();
							let durationSeconds = Math.floor((endTime - startTime1) / 1000);
							if (durationSeconds < 0 || isNaN(durationSeconds)) durationSeconds = 0;
							this.usedTime = this.formatDuration(durationSeconds);
						} else {
							console.log(this.startTime)
							console.log('222')
							this.usedTime = '未记录';
							console.log('⚠️ startTime 获取失败');
						}

						const pages = getCurrentPages();
						const prevPage = pages[pages.length - 2];
						prevPage.$vm.imageUrl = filePath;
						prevPage.$vm.aiUrl = aiUrl;
						prevPage.$vm.usedTime = this.usedTime;
						uni.navigateBack();
					},
					fail: (err) => {
						console.error('上传失败:', err);
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						});
					}
				});
			},
			handleSliderChange(e) {
				this.brushSize = e.detail.value;
				this.ctx.setLineWidth(this.brushSize);
			},
			formatDuration(seconds) {
				// 把秒数格式化成几分几秒
				const m = Math.floor(seconds / 60)
				const s = seconds % 60
				return `${m}分${s}秒`
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f5f7fa;
		overflow: hidden;
	}

	.custom-nav-bar {
		padding: 24rpx 32rpx;
		background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
		padding-top: calc(var(--status-bar-height) + 20rpx);

		.title-container {
			text-align: center;

			.title {
				font-size: 36rpx;
				font-weight: 600;
				color: #2c3e50;
			}

			.subtitle {
				font-size: 24rpx;
				color: #7f8c8d;
				margin-top: 8rpx;
			}
		}
	}

	.tip {
		margin: 20rpx 32rpx;
		padding: 20rpx 28rpx;
		background: #fff9e6;
		border-radius: 16rpx;
		color: #e67e22;
		font-size: 26rpx;
		display: flex;
		align-items: center;
	}

	.main-content {
		flex: 1;
		display: flex;
		padding: 24rpx 32rpx;
		gap: 32rpx;
		min-height: 0;
	}

	.drawing-wrapper {
		flex: 3;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.08);
		overflow: hidden;

		.drawing-area {
			width: 100%;
			height: 100%;

			.drawing-canvas {
				width: 100%;
				height: 100%;
			}
		}
	}

	.toolbar {
		flex: 1;
		min-width: 280rpx;
		max-width: 320rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		display: flex;
		flex-direction: column;
		gap: 24rpx;

		.color-picker {
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 16rpx;

			.color-option {
				aspect-ratio: 1;
				border-radius: 8rpx;
				transition: transform 0.2s;

				&:active {
					transform: scale(0.95);
				}
			}
		}

		.brush-size {
			.label {
				font-size: 28rpx;
				color: #34495e;
				display: block;
				margin-bottom: 16rpx;
			}

			slider {
				/deep/ .uni-slider-track {
					height: 6rpx !important;
				}

				/deep/ .uni-slider-handle {
					width: 32rpx !important;
					height: 32rpx !important;
				}
			}
		}
	}

	.action-footer {
		height: 120rpx;
		padding: 0 32rpx;
		background: #fff;
		border-top: 1rpx solid #eee;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 32rpx;

		.btn {
			height: 80rpx;
			flex: 1;
			max-width: 300rpx;
			font-size: 32rpx;
			transition: opacity 0.2s;

			&:active {
				opacity: 0.8;
			}
		}
	}

	@media (max-width: 768px) {
		.main-content {
			flex-direction: column;
			padding: 24rpx;
		}

		.drawing-wrapper {
			height: 60vh;
			min-height: 400rpx;
		}

		.toolbar {
			max-width: 100%;
			min-width: auto;
		}

		.action-footer {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: 10;
		}
	}
</style>